import 'dart:convert';

import 'package:backend.purchases/infrastructure/dtos/app_store_api/app_store_api_one_time_purchased_item_transaction_dto.dart';
import 'package:backend.purchases/infrastructure/dtos/app_store_api/app_store_api_purchased_subscription_transaction_dto.dart';
import 'package:backend.purchases/infrastructure/dtos/app_store_api/app_store_api_transaction_dto.dart';

final _jsonBase64 = json.fuse(utf8.fuse(base64Url));

String _padBase64(String value) {
  final lenght = value.length;

  switch (lenght % 4) {
    case 2:
      return value.padRight(lenght + 2, '=');
    case 3:
      return value.padRight(lenght + 1, '=');
    default:
      return value;
  }
}

class AppStoreApiTransactionDtoFactory {
  const AppStoreApiTransactionDtoFactory._internal();

  static const _instance = AppStoreApiTransactionDtoFactory._internal();

  factory AppStoreApiTransactionDtoFactory() {
    return _instance;
  }

  AppStoreApiTransactionDto _fromJson(Map<String, dynamic> json) {
    final purchaseType = json['type'];

    if (purchaseType == 'Auto-Renewable Subscription') {
      return AppStoreApiPurchasedSubscriptionTransactionDto.fromJson(json);
    }

    if (purchaseType == 'Non-Consumable') {
      return AppStoreApiOneTimePurchasedItemTransactionDto.fromJson(json);
    }

    throw UnimplementedError();
  }

  AppStoreApiTransactionDto fromJws(String jws) {
    final parts = jws.split('.');
    final json = _jsonBase64.decode(_padBase64(parts[1])) as Map<String, dynamic>;
    return _fromJson(json);
  }
}
